package cn.smile.utils;

import cn.smile.bean.dto.core.SysUserDTO;
import cn.smile.commons.constant.NumberConstant;
import cn.smile.commons.constant.RedisKeyConstant;
import cn.smile.commons.web.Header;
import com.alibaba.fastjson2.JSON;
import org.springframework.util.ObjectUtils;

import java.util.Objects;

public class UserUtil {

    /**
     * 获取当前登录用户信息
     *
     * @return 用户对象
     */
    public static SysUserDTO getUserInfo() {
        RedisUtil redisUtil = new RedisUtil();
        String token = Header.getToken();
        if (ObjectUtils.isEmpty(token)) {
            return getDefaultUser();
        }
        Object bucket = redisUtil.get(String.format(RedisKeyConstant.USER_TOKEN_KEY, token));
        if (Objects.isNull(bucket)) {
            return getDefaultUser();
        }
        return JSON.parseObject(bucket.toString(), SysUserDTO.class);
    }

    /**
     * 缓存中未找到用户, 防治意外, 直接创建一个默认用户对象
     *
     * @return 创建的默认用户
     */
    private static SysUserDTO getDefaultUser() {
        SysUserDTO dto = new SysUserDTO();
        dto.setId("-1");
        dto.setLoginId("unknown");
        dto.setNickName("未知");
        dto.setStatus(NumberConstant.ONE);
        return dto;
    }
}